package xwbank.jmeter5.scripts.dubbo;

import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class CreateBaseRouteInfoTest extends AbstractJavaSamplerClient {
    private static ClassPathXmlApplicationContext context = null;
    private static CmpRouteService cmpRouteService = null;
    private CmpResponse<String> cmpResponse = null;
    private CmpBaseRouteInfoDto cmpBaseRouteInfoDto = null;

    @Override
    public Arguments getDefaultParameters() {
        Arguments arguments = new Arguments();
        arguments.addArgument("channelCode","");
        return arguments;
    }

    @Override
    public void setupTest(JavaSamplerContext context) {
        context = new JavaSamplerContext(new String[] {"/env/serviceperf/dubbo-cmp-consumer.xml"});
        cmpRouteService = context.getBean("cmpRouteService");
        cmpBaseRouteInfoDto = new CmpBaseRouteInfoDto();
        cmpResponse = new CmpResponse<String>();
    }

    @Override
    public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
        String channelCode = javaSamplerContext.getParameter("channelCode");

        SampleResult sampleResult = new SampleResult();
        sampleResult.sampleStart();

        try{
            cmpBaseRouteInfoDto.setChannelCode(channelCode);
            if (cmpResponse.ok()){
                sampleResult.setSuccessful(true);
                sampleResult.setResponseHeaders("response: "+cmpResponse);
                sampleResult.setRequestHeaders("request: " + cmpBaseRouteInfoDto.toString());
                sampleResult.setDataType(SampleResult.TEXT);
            }else {
                sampleResult.setSuccessful(false);
                sampleResult.setResponseHeaders("response: "+cmpResponse);
                sampleResult.setRequestHeaders("request: " + cmpBaseRouteInfoDto.toString());
                sampleResult.setDataType(SampleResult.TEXT);
            }
        }catch (Exception e){
            sampleResult.setSuccessful(false);
            e.printStackTrace();
            System.out.println("fail! " + e.toString());
        }finally {
            sampleResult.sampleEnd();
        }

        return sampleResult;
    }

    @Override
    public void teardownTest(JavaSamplerContext context) {
        super.teardownTest(context);
    }
}
